package net.jxtz.jxtzos.authentication;


import lombok.extern.slf4j.Slf4j;
import net.jxtz.jxtzos.authentication.exception.InvalidJwtTokenException;
import net.jxtz.jxtzos.mapper.redis.RedisMapper;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.AuthorizationServiceException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 *
 * 这个过滤器用于对携带 access-token 的请求执行权限检查
 * 所以, 除了注册端点之外的所有请求都应该被它过滤
 *
 * @author a123
 */
@Slf4j
public class JwtAuthorizationFilter extends OncePerRequestFilter {

    /**
     * 白名单
     */
    public static final Set<String> WHITE_LIST = Stream.of("/authentication/register").collect(Collectors.toSet());

    private final RedisMapper redisMapper;

    public JwtAuthorizationFilter(RedisMapper redisMapper){
        this.redisMapper = redisMapper;
    }


    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        final String token = httpServletRequest.getHeader(JwtUtils.TOKEN_HEAD);
        String requestURI = httpServletRequest.getRequestURI();
        log.info("开始jwt权限校验：" + token);
        // 如果请求头中没有token信息
        if (StringUtils.isBlank(token)){
            // 如果是白名单中的路径
            if (WHITE_LIST.contains(requestURI)) {
                // 放行
                log.info("白名单路径，请求放行");
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }else {
                String s = "非法的访问！";
                log.warn(s);
                throw new AuthorizationServiceException(s);
            }
        }else {
            // 如果请求投中存在token
            final String replaceToken = token.replace(JwtUtils.TOKEN_PREFIX, "");
            final MyUserDetails myUserDetails = JwtUtils.userDetails(replaceToken);
            String cacheToken = (String) redisMapper.get(myUserDetails.getUsername() + JwtUtils.TOKEN_PARAM_PREFIX);
            // 校验token
            if (!token.equals(cacheToken)){
                String s = "过期的token";
                log.warn(s);
                throw new InvalidJwtTokenException(s);
            }else {
                SecurityContextHolder.getContext().setAuthentication(new UsernamePasswordAuthenticationToken(myUserDetails.getUsername(), myUserDetails.getPassword(), myUserDetails.getAuthorities()));
                log.info("权限校验通过，请求放行");
                // 重置token有效期
                redisMapper.expire(myUserDetails.getUsername() + JwtUtils.TOKEN_PARAM_PREFIX, RedisMapper.getOutTime());
                filterChain.doFilter(httpServletRequest,httpServletResponse);
            }
        }
    }
}
